package com.dong.c04_selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2020-03-18 15:24
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //创建实例 / 获取实例
        Selector selector = Selector.open();
        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel注册到selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while(true) {
            //已经把  有事件  发生的  selectionKey 放到了集合
            int select = selector.select(1000);
            //没有事件发生
            if(select==0)  {
                System.out.println("服务器等待了1秒, 无连接");
                continue;
            }
            //有事件发生  select> 0
            //获取到相关selectionKey集合  关注事件的集合
            //通过Selectionkey可以反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while(keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                //关注事件的集合
                int interestOps = key.interestOps();
                //根据key对应的通道发生的事件, 做响应的处理
                if(key.isAcceptable()) {//有新的客户端连接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功: "+socketChannel.hashCode());
                    //将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketchannel注册到selector, 关注事件weOP_READ, 同时给SocketChannel关联一个Buffer
                    //这个 selectionKey   就被管理起来了
                    SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    //  socketChannel.register(selector,SelectionKey.OP_WRITE);
                }else if(key.isReadable()) {
                    //通过key反向获取对应的channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from客户端: "+new String(buffer.array()));
                }
                /**
                 * 手动从集合中移除当前的selectionKey, 防止重复操作
                 */
                keyIterator.remove();
            }
        }
    }
}
